package cn.com.bluemoon.common.permission;

import cn.com.bluemoon.common.KeyAnnotationClz;
import cn.com.bluemoon.daps.api.model.RemoteDataModelRecordService;
import cn.com.bluemoon.daps.common.domain.ResultBean;
import cn.com.bluemoon.daps.common.exception.DapException;
import cn.com.bluemoon.daps.common.toolkit.BmAssetUtils;
import cn.com.bluemoon.daps.model.entity.DapDataModelRecord;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
@Order(Integer.MAX_VALUE - 4)
public class CheckModelIsEdit  {

    @Resource
    private RemoteDataModelRecordService modelRecordService;

    @Pointcut("@annotation(cn.com.bluemoon.common.permission.ModelEdit)")
    public void checkModelIsEdit() {
    }


    @Around("checkModelIsEdit()")
    public Object handlerControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        Method requestMethod = ((MethodSignature) pjp.getSignature()).getMethod();
        ModelEdit modelEdit = requestMethod.getAnnotation(ModelEdit.class);
        if (modelEdit != null) {
            KeyAnnotationClz annotationClz = modelEdit.keyFormClz();
            String modelId = annotationClz.getModelId(pjp);
            if (StringUtils.isNotBlank(modelId)) {
                ResultBean<DapDataModelRecord> rb = modelRecordService.existsRecordByModelId(modelId);
                // 针对编辑 & 查看 & 删除 ；忽略新增的情况（目前只针对数据库中已存在的数据下，进行操作，不存在新增的情况）
                if (rb.getContent() != null) {
                    BmAssetUtils.isTrue(false, () -> new DapException("当前模型处于发布流程中，不允许编辑"));
                } else {
                    log.info("允许编辑");
                }
            } else {
                log.info("允许编辑");
            }
        }
        return pjp.proceed();
    }
}
